package com.asp.aspchain.transaction.service.impl;

import com.alibaba.fastjson.JSON;
import com.asp.aspchain.core.dao.MineringMapper;
import com.asp.aspchain.core.ethereum.EthService;
import com.asp.aspchain.core.model.MgrAccountModel;
import com.asp.aspchain.core.model.MgrNodeModel;
import com.asp.aspchain.core.model.MineringModel;
import com.asp.aspchain.core.util.AjaxResult;
import com.asp.aspchain.transaction.config.MinerListConfig;
import com.asp.aspchain.transaction.request.MineringReq;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.asp.aspchain.transaction.service.AppMineringService;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * Service
 *
 * @author aspire
 * @Date 2018-10-24 11:11
 */
@Service
public class AppMineringServiceImpl implements AppMineringService {

    private static final Logger logger = Logger.getLogger(AppMineringServiceImpl.class);

    @Autowired
    private MinerListConfig minerListConfig;

    @Autowired
    private EthService ethService;

    @Autowired
    private MineringMapper mineringMapper;

    /**
     * 开始挖矿接口(内部接口）
     * @param json
     * @return
     * @author zhongzifeng
     * @date 2018/10/24
     */
    @Override
    public AjaxResult minering(String json){
        AjaxResult result = new AjaxResult();
        Integer accountid;
        String password;
        String hmac;
        MineringReq req = JSON.parseObject(json, MineringReq.class);
        if(req == null){
            logger.error("挖矿失败，json参数为空");
            return new AjaxResult("1","挖矿失败，json参数为空","");
        }
        try {
            Map<String, MgrAccountModel> minerMap = minerListConfig.getMinerMap();
            MgrAccountModel miner = minerMap.get(req.getAccountid());
            if(miner==null){
                logger.error("挖矿失败，未找到相应矿工");
                return new AjaxResult("1","挖矿失败，未找到相应矿工","");
            }
            String minerAccount = miner.getAccountid();
            ethService.setEtherbase(minerAccount);
            ethService.miner();
            // 写入挖矿记录表
            MineringModel minering = new MineringModel();
            MgrNodeModel myNode = minerListConfig.getMgrNode();
            Wrapper<MineringModel> wrapper = new EntityWrapper<>();
            String minerId = "mid"+myNode.getNodeid();
            int mineringCount = mineringMapper.selectCount(wrapper.eq("minerid",minerId));
            minering.setMinerid(minerId);
            minering.setAccountid(req.getAccountid());
            minering.setNodeid(myNode.getNodeid());
            minering.setCreatetime(new Date());
            minering.setUpdatetime(new Date());
            minering.setStarttime(new Date());
            minering.setStatus("01");
            if(mineringCount>0){
                mineringMapper.updateAllColumnById(minering);
            }else{
                mineringMapper.insert(minering);
            }
        } catch (IOException e) {
            logger.error("挖矿失败，"+e.getMessage());
            return new AjaxResult("1","挖矿失败，"+e.getMessage(),"");
        }
        result.setStatus("0");
        result.setMessage("挖矿提交成功");
        return result;
    }

    /**
     * 停止挖矿接口(内部接口）
     * @param json
     * @return
     * @author zhongzifeng
     * @date 2018/10/24
     */
    @Override
    public AjaxResult stopMiner(String json){
        AjaxResult result = new AjaxResult();
        Integer accountid;
        String password;
        String hmac;
        MineringReq req = JSON.parseObject(json, MineringReq.class);
        if(req == null){
            logger.error("停止挖矿失败，json参数为空");
            return new AjaxResult("1","停止挖矿失败，json参数为空","");
        }
        try {
            Map<String,MgrAccountModel> minerMap = minerListConfig.getMinerMap();
            MgrAccountModel miner = minerMap.get(req.getAccountid());
            if(miner==null){
                logger.error("挖矿失败，未找到相应矿工");
                return new AjaxResult("1","挖矿失败，未找到相应矿工","");
            }
            ethService.stopMiner();
            // 写入挖矿记录表
            MineringModel minering = new MineringModel();
            MgrNodeModel myNode = minerListConfig.getMgrNode();
            Wrapper<MineringModel> wrapper = new EntityWrapper<>();
            Integer nodeId = myNode.getNodeid();
            String minerId = "mid"+nodeId;
            String accountId = req.getAccountid();
            minering.setUpdatetime(new Date());
            minering.setEndtime(new Date());
            minering.setStatus("02");
            mineringMapper.update(minering,
                    wrapper.eq("nodeid",nodeId)
                            .eq("minerid",minerId)
                            .eq("accountid",accountId));
        } catch (IOException e) {
            logger.error("停止挖矿失败，"+e.getMessage());
            return new AjaxResult("1","停止挖矿失败，"+e.getMessage(),"");
        }
        result.setStatus("0");
        result.setMessage("停止挖矿提交成功");
        return result;
    }


}
